<template>
  <div class="headers-editor">
    <el-table :data="headers" style="width: 100%">
      <el-table-column width="40">
        <template slot-scope="scope">
          <el-checkbox v-model="scope.row.enabled" />
        </template>
      </el-table-column>
      
      <el-table-column prop="key" label="请求头名称">
        <template slot-scope="scope">
          <el-autocomplete
            v-model="scope.row.key"
            :fetch-suggestions="queryHeaders"
            placeholder="请求头名称"
            size="small"
            style="width: 100%"
            @input="updateHeader(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="value" label="请求头值">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.value"
            placeholder="请求头值"
            size="small"
            @input="updateHeader(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      
      <el-table-column width="80" label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="removeHeader(scope.$index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-button
      type="text"
      size="small"
      @click="addHeader"
      class="add-btn"
    >
      <i class="el-icon-plus"></i> 添加请求头
    </el-button>
  </div>
</template>

<script>
export default {
  name: 'HeadersEditor',
  props: {
    headers: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      commonHeaders: [
        'Accept',
        'Accept-Encoding',
        'Accept-Language',
        'Authorization',
        'Cache-Control',
        'Content-Type',
        'Cookie',
        'Host',
        'Origin',
        'Referer',
        'User-Agent',
        'X-Requested-With'
      ]
    }
  },
  methods: {
    queryHeaders(queryString, cb) {
      const results = queryString
        ? this.commonHeaders.filter(h => 
            h.toLowerCase().includes(queryString.toLowerCase())
          )
        : this.commonHeaders
      cb(results.map(value => ({ value })))
    },
    
    addHeader() {
      this.$emit('add')
    },
    
    updateHeader(index, header) {
      this.$emit('update', { index, header })
    },
    
    removeHeader(index) {
      this.$emit('remove', index)
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../../styles/variables.scss';

.headers-editor {
  .add-btn {
    margin-top: $spacing-base;
  }
}
</style>